﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace ArcGisMapDesktop
{
    public class BusinessRequest
    {
        static readonly List<string> UserAgentPCList = new List<string> { "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
};
        static readonly List<string> UserAgentMoveList = new List<string>
        {"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
       "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36",
       "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36",
       "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36",
       "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"
       };
        static string GetUserAgentPC()
        {
            Random rm = new Random();
            int i = rm.Next(UserAgentPCList.Count);  //随机数最大值不能超过list的总数
            return UserAgentPCList[i];
        }
        static string GetUserAgentMove()
        {
            Random rm = new Random();
            int i = rm.Next(UserAgentPCList.Count);  //随机数最大值不能超过list的总数
            return UserAgentPCList[i];
        }
        public static string PostUrl(string Domain, string url, string postData, string cookieStr, Dictionary<string, string> headDic)// 请求Url，发送数据
        {
            string msg = string.Empty;
            try
            {

                byte[] data = Encoding.UTF8.GetBytes(postData);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();
                if (!string.IsNullOrEmpty(cookieStr))
                {
                    string[] cookstr = cookieStr.Split(';');
                    foreach (string str in cookstr)
                    {
                        if (!string.IsNullOrEmpty(str))
                        {
                            string[] cookieNameValue = str.Split('=');
                            Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                            ck.Domain = Domain;
                            cookieContainer.Add(ck);
                        }
                    }
                }
                foreach (var item in headDic)
                {
                    if (item.Key == "Referer")
                    {
                        request.Referer = item.Value;
                    }
                    else
                        request.Headers.Add(item.Key, item.Value);
                }

                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
               // request.Host = Domain;
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
                request.ContentLength = data.Length;
                //request.
                //request.Referer = "https://www.weimao.com/search?key=%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A7%91&type=enterprise";
                Stream outstream = request.GetRequestStream();

                outstream.Write(data, 0, data.Length);

                outstream.Close();



                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                Stream instream = response.GetResponseStream();

                StreamReader sr = new StreamReader(instream, Encoding.UTF8);

                string content = sr.ReadToEnd();

                return content;
            }
            catch (WebException ex)
            {
                using (var res = (HttpWebResponse)ex.Response)
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        //读取服务器端返回的消息 
                        string content = sr.ReadToEnd();
                        return content;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message);
            }

        }
        /// <summary>
        /// 上传文件 post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, string path)
        {
            try
            {
                // 设置参数

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();

                request.CookieContainer = cookieContainer;

                request.AllowAutoRedirect = true;

                request.Method = "POST";

                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;

                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                int pos = path.LastIndexOf("\\");

                string fileName = path.Substring(pos + 1);

                //请求头部信息 

                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));

                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

                byte[] bArr = new byte[fs.Length];

                fs.Read(bArr, 0, bArr.Length);

                fs.Close();

                Stream postStream = request.GetRequestStream();

                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);

                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                postStream.Write(bArr, 0, bArr.Length);

                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

                postStream.Close();

                //发送请求并获取相应回应数据

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                //直到request.GetResponse()程序才开始向目标网页发送Post请求

                Stream instream = response.GetResponseStream();

                StreamReader sr = new StreamReader(instream, Encoding.UTF8);

                //返回结果网页（html）代码

                string content = sr.ReadToEnd();

                return content;
            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message);
            }

        }
        public static string GetUrl(string Domain, string posturl, Dictionary<string, string> headDic)
        {
            return GetUrl(Domain, posturl, headDic, "", Encoding.Default);
        }
        public static string GetUrl(string Domain, string posturl, Dictionary<string, string> headDic, Encoding encoding)
        {
            return GetUrl(Domain, posturl, headDic, "", encoding);
        }
        public static string GetUrl(string Domain, string posturl, Dictionary<string, string> headDic, string cookieStr)
        {
            return GetUrl(Domain, posturl, headDic, cookieStr, Encoding.Default);
        }
        /// <summary>
        /// get获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetUrl(string Domain, string posturl, Dictionary<string, string> headDic, string cookieStr, Encoding encoding)
        {
            //Stream instream = null;
            //StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            // Encoding encoding = Encoding.UTF8;
            // 准备请求...
            try
            {
                Uri u = new Uri(posturl);

                string sHost = u.Host;
                //string sPort = u.Port;
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                if (!string.IsNullOrEmpty(cookieStr))
                {
                    string[] cookstr = cookieStr.Split(';');
                    foreach (string str in cookstr)
                    {
                        if (!string.IsNullOrEmpty(str) && !str.Contains(","))
                        {
                            string[] cookieNameValue = str.Split('=');
                            Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                            cookieContainer.Add(ck);
                        }
                    }
                }
                foreach (var item in headDic)
                {
                    if (item.Key == "Referer")
                    {
                        request.Referer = item.Value;
                       
                    }
                   else if (item.Key == "Host")
                    {
                        request.Host = item.Value;
                    }
                    else if (item.Key == "UserAgent")
                    {
                        request.UserAgent = item.Value;
                    }
                    else if (item.Key == "Accept")
                    {
                        request.Accept = item.Value; 
                    }
                    else
                        request.Headers.Add(item.Key, item.Value);
                }

                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = GetUserAgentPC(); 
                if (string.IsNullOrEmpty(request.Accept))
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
                string content = string.Empty;
                HttpWebResponse res;
                try
                {
                    using (res = (HttpWebResponse)request.GetResponse())
                    {
                        
                        using (StreamReader sr = new StreamReader(res.GetResponseStream(), encoding))
                        {
                            //读取服务器端返回的消息 
                            content = sr.ReadToEnd();
                        }
                    }
                }
                catch (WebException ex)
                {
                    using (res = (HttpWebResponse)ex.Response)
                    {
                        using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                        {
                            //读取服务器端返回的消息 
                            content = sr.ReadToEnd();
                           
                        }
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message + " UserAgent:" + request.UserAgent);
            }
        }

        /// <summary>
        /// 文件下载方法
        /// </summary>
        /// <param name="posturl"></param>
        /// <returns></returns>
        public static Stream DownloadUrl(string posturl)
        {
            Stream instream = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";

                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                return instream;
            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message);
            }
        }

        /// <summary>
        /// get获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetUrlHtml(string posturl)
        {
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();

                return content;
            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message);
            }
        }
        public static string AjaxGet(string posturl, string Domain = "", string cookieStr = "")
        {
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            // 准备请求...
            try
            {

                Uri u = new Uri(posturl);

                string sHost = u.Host;
                //string sPort = u.Port;
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                if (!string.IsNullOrEmpty(cookieStr))
                {
                    string[] cookstr = cookieStr.Split(';');
                    foreach (string str in cookstr)
                    {
                        if (!string.IsNullOrEmpty(str))
                        {
                            string[] cookieNameValue = str.Split('=');
                            Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
                            ck.Domain = Domain;
                            cookieContainer.Add(ck);
                        }
                    }
                }

                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "text/xml";
                request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();

                return content;

            }
            catch (Exception ex)
            {
                throw new Exception("请检查网络问题，具体错误:" + ex.Message + " UserAgent:" + request.UserAgent);
            }
        }
    }
}
